layui.define(['form','layer','selectTree','common'], function(exports){
    
    // 组装主体html
    var getListHtml = function(data,config){
        //组装展示页面数据
        // 
        var eachData = function(data,depth,ptrDisplay){    
            var returnHtml = '';
            var maxdepth = depth; // 当前dd 或包含子集dd的最深类目
            var dataCount = 0;
            $.each(data,function(k,v){
                if(v.status == 1 )  dataCount++;
            });
            //console.log(dataCount);
            $.each(data,function(key,val){
                var Yd = {up:'<i title="上移动" data-option="up" style="cursor:pointer" class="layui-icon layui-icon-up"></i>',
                    down:'<i title="下移动" data-option="down" style="cursor:pointer" class="layui-icon layui-icon-down"></i>',
                    left:'<i title="左移动" data-option="left"  style="cursor:pointer" class="layui-icon layui-icon-left"></i>',
                    right:'<i title="右移动" data-option="right" style="cursor:pointer" class="layui-icon layui-icon-right"></i>'};
                var trMaxDepth = depth;
                var tempHtml = {html:'',depth:depth};
                var thisCss = {childicon:'<i class="e_icon_block"></i>'};
                
                // 展开和收起
                var trDisplay = '';
                if( typeof val.display != 'undefined'){
                    trDisplay =  val.display == 'hide' ? 'style="display: none;"':'';
                }else if(ptrDisplay){
                    trDisplay = ptrDisplay;
                }
                
                if( typeof val.child == 'object' && typeof val.child[0] != 'undefined' ){
                     tempHtml = eachData(val.child , depth + 1,trDisplay);
                     trMaxDepth = tempHtml.depth > trMaxDepth ? tempHtml.depth : trMaxDepth;
                     maxdepth = tempHtml.depth > maxdepth ? tempHtml.depth : maxdepth;
                     thisCss.childicon = '<i data-option="hide" style="cursor:pointer" class="layui-icon layui-icon-triangle-d"></i>';
                     if(trDisplay !=''){
                        thisCss.childicon = '<i data-option="show" style="cursor:pointer" class="layui-icon layui-icon-triangle-r "></i>';
                     }
                }
                /*
                if( key == 0 ) Yd.up = '<i data-option="up" style="cursor: not-allowed; color: #eee;" class="layui-icon layui-icon-up e-disable"></i>';
                if( key+1 == dataCount ) Yd.down = '<i data-option="down" style="cursor: not-allowed; color: #eee;" class="layui-icon layui-icon-down e-disable"></i>';
                if( depth == 1 ) Yd.left = '<i data-option="left" style="cursor: not-allowed; color: #eee;" class="layui-icon layui-icon-left e-disable"></i>';
                if( depth == 3 ) Yd.right = '<i data-option="right" style="cursor: not-allowed; color: #eee;" class="layui-icon layui-icon-right e-disable"></i>';
                */
                if( key == 0 ) Yd.up = '';
                if( key+1 == dataCount ) Yd.down = '';
                if( depth == 1 ) Yd.left = '';
                if( trMaxDepth >= config.maxdepth || key ==0 ) Yd.right = '';                
                if( val.status != 1 ) Yd = {up:'',down:'',left:'',right:''};
                
                
                
                returnHtml += '<tr '+ptrDisplay+' class="nodelist JF_pid_'+val.pid+'" data-maxdepth="'+trMaxDepth+'"  data-pid="'+val.pid+'" data-id="'+val.id+'" data-depth="'+depth+'" data-name="'+val.groupname+'">'
                    +'<td class="td_left">'
                    +'    <div class="layui-table-cell ">'+val.id+'</div>'
                    +'</td>'                
                    +'<td class="td_left">'
                    +'    <div style="padding-left: 10px;" class="layui-table-cell e-sort-depth'+depth+'">'
                    + thisCss.childicon
                    +'        <span class="JS_edit">'+val.groupname+'</span>'
                    +'    </div>'
                    +'    <input style="display: none;" value="'+val.groupname+'" class="layui-input layui-table-edit JS_edit_input" />'
                    +'</td>'
                    +'<td class="td_left">'
                    +'    <div class="layui-table-cell" style="text-align: center;">'
                    +Yd.left
                    +Yd.up
                    +Yd.down
                    +Yd.right                  
                    +'    </div>'
                    +'</td>'
                    +'<td class="td_left">'
                    +'    <div class="layui-table-cell layui-inline" style="height:auto;">'
                    +'        <input class="JS_status" '+( val.status ==1?"checked":"" )+' lay-filter="JF_treeStatus" type="checkbox" data-id="'+val.id+'" lay-skin="switch" lay-text="正常|关闭">'
                    +'    </div>'
                    +'</td>'
                +'</tr>';
                returnHtml += tempHtml.html;
            });
            return {html:returnHtml,depth:maxdepth};
        }
        var liHtml = eachData(data,1);
        var html = '<form class="layui-form"><table cellspacing="0" cellpadding="0" border="0" style="width: 100%;" class="layui-table">'
                +'<thead ' + (liHtml.html==''?'style="display: none;"':'') + '>'
                +'    <tr>'
                +'        <th style="width: 40px;">ID</th>'
                +'        <th>分类名称</th>'
                +'        <th style="width: 80px;">排序</th>'
                +'        <th style="width: 80px;">状态</th>'
                +'    </tr>'
                +'</thead>'
                +'<tbody id="JS_box">'
                + liHtml.html
                +'</tbody>'
                +'</table>'
               // +'<div class="layui-layout-admin" >'
               // +'<div class="layui-footer" style="left:0;">'
                +'<div style="text-align: right;  ">'
              //  +'    <a href="javascript:;" id="JS_close" class="layui-btn layui-btn-primary layui-btn-sm">关闭</a>'
                +'    <a href="javascript:;" id="JS_sortTree_save" class="layui-btn layui-btn-sm">保存或关闭</a>'        
                +'    <a href="javascript:;" id="JS_sortTree_addBtn" class="layui-btn layui-btn-normal layui-btn-sm">新增分类</a>'
                +'</div>'
               // +'</div>'
                +'</form>'        
        return html;
    }
    
    // 组装新增Html
    var getAddHtml = function(){
       // var html = '<div id="JS_alert_box" style="padding: 30px 60px; 60px 60px">'
        var html = '<div class="layui-form-item">'
            +'	<div class="layui-input-inline">'
            +'		<input type="text" name="name" value="" placeholder="分类名称" lay-verify="required" class="layui-input" />'
            +'	</div>'    
            +'</div>'
            +'<div class="layui-form-item">'
            +'	<div class="layui-input-inline" id="JF_SortTree_select" >'                    
            +'    </div>'     
            +'</div>'
            +'<div style="text-align: right; padding-right: 20px;">'
            +'    <a href="javascript:;" id="JS_add_close" class="layui-btn layui-btn-primary layui-btn-sm">取消</a> '
            +'    <a href="javascript:;" id="JS_add_save" class="layui-btn layui-btn-sm">确定</a>'        
          //  +'</div>'
        +'</div>';
        return html;
    }
    
    // 各种事件的处理
    var lockEdit = false;  //  标识数据是否被修改过 
    var events = function(rElem,data,config,initCall){        
        layui.form.render('checkbox');
        var icon = rElem.find('.layui-icon');           
        // 保存数据
        rElem.find('#JS_sortTree_save').on('click',function(){
            var saveData = new Array();
            $.each(data,function(k,v){
                if( v.status == 1 ) saveData.push(v); 
            });
            var backFunc = function(ret){
                if( ret.code == 1){
                    console.log(saveData);
                    if( typeof config.done == 'function' ) config.done(saveData);
                    layui.layer.closeAll();
                }else{
                    layui.common.error(ret.msg);
                }
            }
            if( lockEdit ){
                lockEdit = false;
                layui.common.post(config.urledit,{data:saveData},backFunc);
            }else{
                if( typeof config.done == 'function' ) config.done(saveData);
                layui.layer.closeAll();
            }            
        });   
        
        // 新增分类
        rElem.find('#JS_sortTree_addBtn').on('click',function(){            
            var addHtml = getAddHtml();            
            var index = layer.open({
                title : '添加分类',
                type: 1,
                skin: 'layui-layer-adminshow', //样式类名
                closeBtn: 0, //不显示关闭按钮
                anim: 2,
                shadeClose: true, //开启遮罩关闭
                content: '<div id="JS_alert_box" style="padding: 30px 60px; 60px 60px"></div>'
            });
            var addElem = $(addHtml);
            $('#JS_alert_box').html('').html(addElem);
            
            var pid = 0;     // 父级ID
            var dataList = new Array();
            $.each(data,function(k,v){
                if( v.status == 1 ) dataList.push(v);
            });
            
            var select = layui.selectTree.render({
                elem : '#JF_SortTree_select', //绑定的容器元素
                data : dataList, //展示的数据 和 url 赋值其中一个 data 优先 没有的话从接口获取数据
                //checkid : 7, // 数据选中的ID
                maxdepth : config.maxdepth -1,
                name : 'group', // 生成的表单名称
                done : function(val){
                    pid = val.id;
                },
                field : config.field
            });
            addElem.find('#JS_add_close').on('click',function(){
                layui.layer.close(index); 
            });
            addElem.find('#JS_add_save').on('click',function(){
                var val = addElem.find('input[name="name"]').val();
                if( val == ''){
                    layui.layer.close(index); 
                    return false;
                }
                $.post(config.urladd,{pid:pid,name:val},function(ret){
                    if( ret.code == 1){                        
                        layui.layer.close(index); 
                        initCall(ret.data);
                    }else{
                        layui.common.error(ret.msg);
                    }
                },'json');
                
            });
        });
        
        // 编辑
        rElem.find('.JS_edit').on('click',function(){
            var v = $(this).parents('.td_left').find('input').val();
            $(this).parents('.td_left').find('input').show().focus().val('').val(v); 
        });
        rElem.find('.JS_edit_input').on('blur',function(){
            $(this).hide();
            var vname = $(this).val();
            $(this).parents('td').find('.JS_edit').text(vname);
            $(this).parents('tr').data('name',vname);
            var eachData = function(data,id){
                $.each(data,function(k,v){
                    if( v[config.field.id] == id ){
                        v[config.field.name] = vname;
                    }
                    if( typeof v[config.field.child] == 'object' && typeof v[config.field.child][0] != 'undefined' ){
                        eachData(data[k][config.field.child],id);
                    }
                });
            }
            var id = $(this).parents('tr').data('id');
            eachData(data,id);
            lockEdit = true;
        });
        
         
        //关闭和开启处理
        layui.form.on('switch(JF_treeStatus)', function (data){
            var id = $(data.elem).data("id");
            var ischecked = data.elem.checked;
            $.post(config.urleditstatus,{id:id},function(ret){
                if(ret.code!=1){
                    if(ret.code == 2){
                        layer.msg('正在处理中,请别着急...');
                    }else{
                        layer.msg(ret.msg);
                    }                    
                    if(ischecked){
                        $(data.elem).prop("checked",false);
                        $(data.othis).removeClass("layui-form-onswitch").find("em").text("关闭");
                    }else{
                        $(data.elem).prop("checked",true);
                        $(data.othis).addClass("layui-form-onswitch").find("em").text("正常");
                    }
                }else{
                    initCall(ret.data);
                }
            });            
            return false;
        });
        
        // 移动和展开的点击事件
        icon.on('click',function(){
            var thisOption = $(this).data('option');                        
            
            if( thisOption == 'show' || thisOption == 'hide' ){ // 展开
                var triggerShow = function(eThis,action,closeChild){
                    var eid  = closeChild == true ? eThis : eThis.parents('tr').data('id');
                    if( action == 'show'){
                        if(!closeChild) eThis.data('option','hide');
                        $(rElem).find('tr.JF_pid_'+eid).show();
                    }else{
                        if(!closeChild) eThis.data('option','show');
                        $(rElem).find('tr.JF_pid_'+eid).hide();
                    }                    
                    $.each($(rElem).find('tr.JF_pid_'+eid),function(sk,sv){
                         triggerShow($(this).data('id'),action,true);
                    });
                }
                
                var tagData = function(data,id,thisOption){
                    $.each(data,function(k,v){
                        if( v[config.field.id] == id ){
                            data[k]['display'] = thisOption;
                        }
                        if( typeof v[config.field.child] == 'object' && typeof v[config.field.child][0] != 'undefined' ){
                            tagData(data[k][config.field.child],id,thisOption);
                        }
                    });
                }
                
                triggerShow($(this),thisOption);
                tagData(data,$(this).parents('tr').data('id'),thisOption);
                thisOption == 'hide' && $(this).removeClass('layui-icon-triangle-d').addClass('layui-icon-triangle-r');
                thisOption == 'show' && $(this).removeClass('layui-icon-triangle-r').addClass('layui-icon-triangle-d');                
            }            
            if( thisOption == 'up' || thisOption == 'down' || thisOption == 'left' || thisOption == 'right' ){ //移动 
                moveAction($(this),data,thisOption);
                lockEdit = true;
            }
        });
        
        // 移动操作处理 eThis 被移动的对象 toE移动的信息
        var moveAction = function(eThis,data,direction){
            var eid  = eThis.parents('tr').data('id');            
            // 当前数据 查找处理ID，操作类型 ，父级数据 ，父级索引
            var changeData = function(data,id,direction,pdata,pkey){ 
                var returnData = '';   
                var isGet = false;
                $.each(data,function(k,v){
                    if( v[config.field.id] == id ){
                        if( direction == 'up' ){
                            data[k] = data[k-1];
                            data[k-1] = v;
                        }else if(direction == 'down'){
                            data[k] = data[k+1];
                            data[k+1] = v; 
                        }else if(direction== 'left'){
                            if( ! pdata ){
                                console.log('顶级分类无法向上移动');
                                return false;
                            }
                            data.splice(k,1);   // 把找到的数据从原来的位置删除                            
                            var newChild = v;
                            newChild[config.field.pid] = pdata[pkey][config.field.pid];
                            pdata.splice(pkey+1,0,newChild);   
                            returnData = data             
                        }else if(direction== 'right'){
                            data.splice(k,1);   // 把找到的数据从原来的位置删除
                            var newChild = v;
                            newChild[config.field.pid] = data[k-1][config.field.id];
                            data[k-1][config.field.child].push(newChild);
                            returnData = data                            
                        }
                        isGet = true;
                        return false;                        
                    }
                    if( typeof v[config.field.child] == 'object' && typeof v[config.field.child][0] != 'undefined' ){
                        var childData = data[k][config.field.child];
                        var ret =  changeData(childData,id,direction,data,k);
                        if( ret.isGet ){
                            data[k][config.field.child] = ret.list;
                            isGet = true;
                            return false;
                        }
                        
                    }
                });
                return {list:data,isGet:isGet};
            } 
                        
            var ret = changeData(data,eid,direction);
            initCall(ret.list);            
        }
    }
    
    var listSortTree = function(options){
        var that = this;
        if(options.urladd==''||options.urledit==''||options.urleditstatus=='' ) alert('url参数错误');
        that.config = {
            data    : '', // 外部传进来的数据 优先于 url ，当 data 等于 '' 的时候从接口url获取
            url     : '/set/casesgroup/ajaxlist', // 指定数据获取接口 
            urladd  : '/set/casesgroup/add',
            urledit : '/set/casesgroup/edit',
            urleditstatus : '/set/casesgroup/editstatus',
            maxdepth : 3,  // 最多可以加编辑成多少层级
            done  : function(){},
            field : {
                id      : 'id',     // 上传表单的值对应的字段
                name    : 'groupname',   // 显示的名称
                depth   : 'depth',   // 级别字段
                child   : 'child',   // 子集字段标识
                pid     : 'pid',     // 父级ID标识
            }
        }
        $.extend(true,that.config,options);
        
        
        var index = layer.open({
            title : '分类管理',
            area : ['600px', '480px'],
            type: 1,
            skin: 'layui-layer-admin', //样式类名
            closeBtn: 0, //不显示关闭按钮
            anim: 2,
           // shadeClose: true, //开启遮罩关闭
            content: '<div id="JF_sortTree_mian" style="padding: 10px 20px 30px 20px;"></div>'
        });
        var runInit = function(data){
            var html = getListHtml(data,that.config);
            var Elem = $(html);
            $('#JF_sortTree_mian').html('').html(Elem);
            events(Elem,data,that.config,runInit);
        }
        if( that.config.data == ''){
            $.get(that.config.url,{},function(ret){
                //console.log(ret);
                if( ret.code == 1){
                   // console.log( '111');
                   // console.log(ret.data);
                    runInit(ret.data);
                }else{
                    layui.layer.alert(ret.msg);
                }  
            },'json');            
        }else{
            runInit(that.config.data);
        }
    }
    
    
    
    var sortTree = {        
        render:function(options){
            return new listSortTree(options);           
        }
        
    }
    
    exports('sortTree', sortTree);
});